package com.janson.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.janson.entity.User;
import com.janson.entity.UserInfo;
import com.janson.service.impl.UserInfoServiceImpl;
import com.janson.service.impl.UserServiceImpl;
import com.janson.utils.MyUtils;
import com.janson.vo.RegisterForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @Author Janson
 * @Date 2022/3/29 16:27
 * @Version 1.0
 */
@Controller

public class LoginController {
    @Autowired
    UserServiceImpl userService;

    @Autowired
    UserInfoServiceImpl userInfoService;
    @GetMapping({"/","/index"})
    public String index(){
        return "index";
    }
    @GetMapping("/register")
    public String register(){
        return "register";
    }

    @GetMapping("/toLogin")
    public String login(){
        return "login";
    }
    @PostMapping("/register")
    public String register(RegisterForm registerForm, Model model){
        //密码重复判断
        if (!registerForm.getPassword().equals(registerForm.getRepassword())){
            model.addAttribute("registerMsg","两次输入密码不一致");
            return "register";
        }
        //用户名重复判断
        String username = registerForm.getUsername();
        User hasuser = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (hasuser!=null){
            model.addAttribute("registerMsg","用户名已存");
            return "register";
        }
        User user = new User();
        user.setUid(MyUtils.getUID());
        user.setUsername(username);
        user.setPassword(new BCryptPasswordEncoder().encode(registerForm.getPassword()));
        user.setGmtCreate(MyUtils.getTime());
        user.setLoginDate(MyUtils.getTime());
        user.setRoleId(2);
        boolean save = userService.save(user);
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(user.getUid());
        userInfoService.save(userInfo);
        if (save){
            model.addAttribute("registerMsg","注册成功");
        }
        return "redirect:/toLogin";
    }
}
